package cn.xspace.module.other.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.xspace.android.imcommon.utils.AppUtil;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.PreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.module.other.R;
import okhttp3.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AboutActivity extends BaseActivity {

    private static final String TAG = AboutActivity.class.getSimpleName();

    private String qrCodeUrl;

    public static final String V = " V";
    public String versions = V + "1.0.0";

    private TitleBar mTitleBar;
    private ImageView mAboutAppLogo;
    private ImageView mAboutaQrcodeIcon;
    private TextView mAboutactVersionCodeTxt;
    private TextView mCopyright;
    private TextView mCompanyName;
    private TextView mCompanyNetIcp;
    private File localFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppUtil.createDirs();
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_about);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.about_title_bar);
        mTitleBar.setRightLayoutVisibility(View.GONE);
        mTitleBar.setTitle(String.format(getString(R.string.setting_about_app_name), getString(R.string.app_name)));
        mAboutAppLogo = (ImageView) findViewById(R.id.iv_app_logo);
        mAboutaQrcodeIcon = (ImageView) findViewById(R.id.iv_qrcode_icon);
        mAboutactVersionCodeTxt = (TextView) findViewById(R.id.aboutact_version_code_txt);
        mCopyright = (TextView) findViewById(R.id.copyright);
        mCompanyName = (TextView) findViewById(R.id.company_name);
        mCompanyNetIcp = (TextView) findViewById(R.id.company_net_icp);


        String version = MyInfoUtil.getAppInfo(mContext).app_version;
        if (!TextUtils.isEmpty(version)) {
            versions = V + version;
        }
        mAboutactVersionCodeTxt.setText(MyInfoUtil.getAppInfo(mContext).app_deptname + getString(R.string
                .app_system) + versions);
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_logo);
        mAboutAppLogo.setImageBitmap(bmp);
    }

    @Override
    protected void initData() {
        localFile = new File(AppConstant.QR_CODE_PATH);
        qrCodeUrl = PreferencesUtils.getStringData(Constants.QR_CODE_URL);
        if (localFile.exists() && localFile.length() > 0) {
            Picasso.with(mContext)
                    .load(localFile)
                    .into(mAboutaQrcodeIcon);
        } else if (!TextUtils.isEmpty(qrCodeUrl)) {
            Picasso.with(mContext)
                    .load(qrCodeUrl)
                    .into(mAboutaQrcodeIcon);
            downloadAndSaveQrCode();
        } else {
            queryQRCode();
        }
        unionOrgAction();
    }

    private void queryQRCode() {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("deptid", MyInfoUtil.getAppOrgId());
        OkHttpManager.getInstance().commonJsonPost(Constants.queryQRCode, hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(String result) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            qrCodeUrl = jsonObject.optString("desc");
                            Picasso.with(mContext)
                                    .load(qrCodeUrl)
                                    .into(mAboutaQrcodeIcon);
                            if (!TextUtils.isEmpty(qrCodeUrl)) {
                                PreferencesUtils.SaveStringData(Constants.QR_CODE_URL, qrCodeUrl);
                                downloadAndSaveQrCode();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 下载并保存二维码
     */
    private void downloadAndSaveQrCode() {
        OkHttpManager.getInstance().downloadFile(qrCodeUrl)
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Response>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Response response) {
                        InputStream is = response.body().byteStream();
                        FileOutputStream fOut;
                        try {
                            fOut = new FileOutputStream(localFile);
                            BitmapFactory.Options ops = new BitmapFactory.Options();
                            ops.inJustDecodeBounds = false;
                            Bitmap mBitmap = BitmapFactory.decodeStream(is, null, ops);
                            //将bitmap存储为jpg格式的图片
                            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                            fOut.flush();//刷新文件流
                            fOut.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (is != null) {
                                try {
                                    is.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected void initEvent() {
        mTitleBar.setLeftLayoutClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void unionOrgAction() {
        if (!Constants.UnionOrgId.equalsIgnoreCase(MyInfoUtil.getAppOrgId())) {
            mCompanyNetIcp.setVisibility(View.INVISIBLE);
        } else {
            queryCopyRight();
        }
    }

    private void queryCopyRight() {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("deptid", MyInfoUtil.getAppOrgId());
        OkHttpManager.getInstance().commonRequestWithoutEncrypt(Constants.queryCopyRight, hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        try {
                            JSONObject jsonObject = new JSONObject(baseReturnBean.data);
                            String copyright = jsonObject.optString("app_copyright");
                            String support_company = jsonObject.optString("app_supportname");
                            mCopyright.setText(Html.fromHtml("<b><tt>版权所有</tt></b> © " + copyright));
                            mCompanyName.setText(Html.fromHtml("<b><tt>技术支持</tt></b>：" + support_company));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

//    private void WriteData() {
//        String text = null;
//        try {
//            InputStream is = getAssets().open("/www/breed/table_list.html");
//            text = readTextFromSDCard(is);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        try {
//            FileOutputStream fos = openFileOutput("aa.html", Context.MODE_PRIVATE);
//            String inputFileContext = text;
//            fos.write(inputFileContext.getBytes());
//            fos.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }
//
//    private String readTextFromSDCard(InputStream is) throws Exception {
//        InputStreamReader reader = new InputStreamReader(is);
//        BufferedReader bufferedReader = new BufferedReader(reader);
//        StringBuffer buffer = new StringBuffer("");
//        String str;
//        while ((str = bufferedReader.readLine()) != null) {
//            buffer.append(str);
//            buffer.append("\n");
//        }
//        return buffer.toString();
//    }

}
